var pomelo = window.pomelo;

var host = '127.0.0.1', gatePort = 3014, connPort = 3050;

if (location.protocol === 'file:') {
    alert('请勿使用文件方式打开！');
    log('请勿使用文件方式打开！');
}

var params = location.search.split('?')[1].split('_');
var gameId = params[0] || 5,
    playerId = params[1] || 1004,
    token = params[2];
var playerType = {
    0: '玩家',
    1: '观察者'
};

document.title = playerId;

var gameOperate = new Vue({
    el: '#gameOperate',
    data: {
        gameId: gameId,
        playerId: playerId,
        roomData: {},
        rid: 1,
        bidNum: 0,
        counter: 0,
        msgs: []
    },
    methods: {
        clearMsgs: function () {
            this.msgs = [];
        },
        enterGame: function (cb) {
            var self = this;
            console.log('enterGame');
            var playerId = self.playerId, gameId = this.gameId;
            // this.msgs.push('进入游戏：' + this.gameId);
            pomelo.init(
                {
                    host: '127.0.0.1',
                    port: connPort,
                    log: true
                },
                function () {
                    var route = router.enterGame;
                    pomelo.request(
                        route,
                        {
                            playerId,
                            token,
                            gameId
                        },
                        function (data) {
                            console.table(data.roomData);
                            var playerInfo;
                            for (var v in data.roomData) {
                                playerInfo = data.roomData[v];
                                playerInfo.type = playerType[playerInfo.type];
                            }
                            self.roomData = data.roomData;
                            if (data.err) {
                                log('用户进入游戏失败：', data.err);
                                self.msgs.push('返回消息：游戏' + self.gameId + '：用户' + playerId + '进入游戏失败！err: ' + data.err);
                            }
                            else {
                                log('用户进入游戏正常！');
                                if (typeof cb === 'function') {
                                    cb();
                                }
                                // self.msgs.push('游戏' + gameId + '：用户' + playerId + '进入游戏！');
                            }
                        });
                });
        },
        autoReady: function () {
            var self = this;
            self.enterGame(function () {
                log('进入游戏成功！');
                self.enterRoom(function () {
                    log('进入房间成功！');
                    self.gameReady();
                });
            });
        },
        leaveGame: function () {
            log('leaveGame');
            var self = this;
            self.msgs.push('返回消息：游戏' + self.gameId + '：用户' + playerId + '退出游戏！');
            this.roomData = {};
            pomelo.disconnect();
        },
        enterRoom: function (cb) {
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            var route = router.enterRoom;
            pomelo.request(
                route,
                {
                    playerId,
                    rid,
                    gameId,
                    pos: 1
                },
                function (data) {
                    // log(data);
                    if (data.err) {
                        log('用户进入房间失败：', data.err);
                        // this.msgs.push('玩家：' + this.playerId + '退出游戏！');
                        self.msgs.push('返回消息：游戏' + self.gameId + '：用户' + playerId + '进入房间失败！err: ' + data.err);
                    }
                    else {
                        log('用户进入房间正常！');
                        if (typeof cb === 'function') {
                            cb();
                        }
                        // self.msgs.push('游戏' + self.gameId + '：用户' + playerId + '进入房间 ' + self.rid + '！');
                        // self.roomData[playerId] = { playerId, rid };
                    }
                });
        },
        leaveRoom: function () {
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.leaveRoom;
            pomelo.request(
                route,
                {
                    playerId,
                    rid,
                    gameId
                },
                function (data) {
                    log('用户退出房间：', data);
                    if (data.err) {
                        self.msgs.push('游戏' + self.gameId + '：用户' + playerId + '退出房间失败！err: ' + data.err);
                    }
                    else {
                        // self.msgs.push('游戏' + self.gameId + '：用户' + playerId + '退出房间' + self.rid + '！');
                        // delete self.roomData[playerId];
                    }
                });
        },
        gameReady: function () {
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.gameReady;
            pomelo.request(
                route,
                {
                    playerId,
                    rid,
                    gameId
                },
                function (data) {
                    log('用户准备游戏：', data);
                    if (data.err) {
                        self.msgs.push('返回消息：游戏' + gameId + '：用户' + playerId + '准备失败！err: ' + data.err);
                    }
                    else {
                        // self.msgs.push('游戏' + self.gameId + '：用户' + playerId + '退出房间' + self.rid + '！');
                        // delete self.roomData[playerId];
                    }
                });
        },
        bid: function () {
            log('下注！');
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.bid, bidNum = this.bidNum || 1.1;
            pomelo.request(
                route,
                {
                    playerId,
                    bid: bidNum,
                    rid
                },
                function (data) {
                    log('用户准备游戏：', data);
                    if (data.err) {
                        self.msgs.push('返回消息：游戏' + gameId + '：用户' + playerId + '下注失败！err: ' + data.err);
                    }
                });
        },
        applyBanker: function () {
            log('申请上庄！');
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.applyBanker;
            pomelo.request(
                route,
                {
                    playerId,
                    apply: true,
                    rid
                },
                function (data) {
                    log('用户准备游戏：', data);
                    if (data.err) {
                        self.msgs.push('返回消息：游戏' + gameId + '：用户' + playerId + '上庄失败！err: ' + data.err);
                    }
                });
        },
        notApplyBanker: function () {
            log('申请上庄！');
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.applyBanker;
            pomelo.request(
                route,
                {
                    playerId,
                    apply: false,
                    rid
                },
                function (data) {
                    log('用户准备游戏：', data);
                    if (data.err) {
                        self.msgs.push('返回消息：游戏' + gameId + '：用户' + playerId + '不上庄失败！err: ' + data.err);
                    }
                });
        },
        nextRound: function () {
            log('下注！');
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.nextRound;
            pomelo.request(
                route,
                {
                    playerId,
                    rid
                },
                function (data) {
                    log('用户准备游戏：', data);
                    if (data.err) {
                        self.msgs.push('返回消息：游戏' + gameId + '：用户' + playerId + '申请下一轮失败！err: ' + data.err);
                    }
                });
        },
        addObserver: function () {
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.addObserver;
            pomelo.request(
                route,
                {
                    playerId,
                    rid,
                    gameId
                },
                function (data) {
                    log('用户观察游戏：', data);
                    if (data.err) {
                        self.msgs.push('返回消息：游戏' + gameId + '：用户' + playerId + '观察失败！err: ' + data.err);
                    }
                    this.roomData = data;
                });
        },
        getWaitRoom: function () {
            var self = this;
            var gameId = this.gameId, playerId = this.playerId, rid = this.rid;
            route = router.getWaitRoom;
            pomelo.request(
                route,
                { },
                function (data) {
                    log('获取才只有一个人的房间号：', data);
                    if (data.err) {
                        self.msgs.push('返回消息：游戏' + gameId + '：获取才只有一个人的房间号失败！err: ' + data.err);
                    }
                    self.msgs.push('返回消息：游戏' + gameId + '：可快速加入的房间号为：' + data.rid);
                });
        }
    }
});

var router = {
    enterGame: 'connector.entryHandler.enterGame',
    enterRoom: 'ernn.gameHandler.enterRoom',
    addObserver: 'ernn.gameHandler.addObserver',
    leaveRoom: 'ernn.gameHandler.leaveRoom',
    gameReady: 'ernn.gameHandler.gameReady',
    applyBanker: 'ernn.gameHandler.applyBanker',
    bid: 'ernn.gameHandler.bid',
    nextRound: 'ernn.gameHandler.nextRound',
    getWaitRoom: 'ernn.gameHandler.getWaitRoom'
};

var events = {
    onGameEnter: 'onGameEnter',
    onPlayerEnter: 'onPlayerEnter',
    onPlayerLeave: 'onPlayerLeave',
    onPlayerEnterRoom: 'onPlayerEnterRoom',
    onPlayerLeaveRoom: 'onPlayerLeaveRoom',
    onGameReady: 'onGameReady',
    onGameReady: 'onGameReady',
    onObserverEnter: 'onObserverEnter',
    onSetBanker: 'onSetBanker',
    onBid: 'onBid',
    onGameOver: 'onGameOver',
    onPlayer1Apply: 'onPlayer1Apply',
    onPlayer2Apply: 'onPlayer2Apply',
    onRoomCalc: 'onRoomCalc',

    onGameXiaZhu: 'onGameXiaZhu',
    onGameKaiPai: 'onGameKaiPai',
    onGameFree: 'onGameFree',
    onGameStart: 'onGameStart',
    onGameBid: 'onGameBid',
    
    onCalcResult: 'onCalcResult',
    onCancelBanker: 'onCancelBanker',
    onApplyBanker: 'onApplyBanker',
    onCutInBanker: 'onCutInBanker'
};



pomelo.on(events.onGameEnter, function (data) {
    var eve = 'onGameEnter';
    var msg = `playerId: ${data.playerId}, playerName:  ${data.playerName}, coin:  ${data.coin}, roundCount:  ${data.roundCount}, score:  ${data.score}`;
    bold(eve, msg);
    // dir(data);
    gameOperate.msgs.push('广播：游戏' + gameId + '：用户' + data.playerId + '进入游戏！');
});

pomelo.on(events.onPlayerLeave, function (data) {
    var eve = 'onPlayerLeave';
    var msg = `playerId: ${data.playerId}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏' + gameId + '：用户' + data.playerId + '退出游戏！');
    delete gameOperate.roomData[data.playerId];
});

// 用户进入房间
pomelo.on(events.onPlayerEnterRoom, function (data) {
    var eve = 'onPlayerEnterRoom';
    var msg = `playerId: ${data.playerId}, rid:  ${data.rid}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：用户' + data.playerId + '进入房间 ' + data.rid + '！');
    gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type], coin: data.coin };
});

// 用户进入房间
pomelo.on(events.onPlayerEnter, function (data) {
    var eve = 'onPlayerEnter';
    var msg = `playerId: ${data.playerId}, rid:  ${data.rid}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：用户' + data.playerId + '进入房间 ' + data.rid + '！coin: ' + data.coin);
    gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type], coin: data.coin };
});

// 用户离开房间
pomelo.on(events.onPlayerLeaveRoom, function (data) {
    var eve = 'onPlayerLeaveRoom';
    var msg = `playerId: ${data.playerId}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：用户' + data.playerId + '离开房间 ' + data.rid + '！');
    delete gameOperate.roomData[data.playerId];
});

// 观察者进入房间
pomelo.on(events.onObserverEnter, function (data) {
    var eve = 'onObserverEnter';
    var msg = `playerId: ${data.playerId}`;
    bold(eve, msg);
    // gameOperate.msgs.push('观察者进入房间');
    gameOperate.msgs.push('广播：游戏5：观察者' + data.playerId + '进入房间 ' + gameOperate.rid + '！');
    gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: gameOperate.rid, type: playerType[data.type], coin: data.coin };
});


// 向大厅用户广播房间结算信息
pomelo.on(events.onRoomCalc, function (data) {
    var eve = 'onRoomCalc';
    var msg = `data: ${data}`;
    bold(eve, msg);
    // gameOperate.msgs.push('观察者进入房间');
    gameOperate.msgs.push('广播：游戏5：向大厅用户' + gameOperate.playerId + '广播房间结算信息: ' + JSON.stringify(data));
    for (playerId in data) {
        gameOperate.roomData[playerId].coin = data[playerId].coin;
    }

    // setTimeout(function () {
    //     gameOperate.msgs = [];
    // }, 1000);
});

// 用户准备游戏
pomelo.on(events.onGameReady, function (data) {
    var eve = 'onGameReady';
    var msg = `playerId: ${data.playerId}, rid:  ${data.rid}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：房间' + data.rid + ' 用户' + data.playerId + '准备游戏！');
    // gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type] };
});

// 用户上庄
pomelo.on(events.onSetBanker, function (data) {
    var eve = 'onSetBanker';
    var msg = `banker: ${data.banker}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：房间' + gameOperate.rid + ' 用户' + data.banker + '上庄成功!');
    gameOperate.msgs.push('下注选择：[' + data.bidList + ']');
    // gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type] };
});

// 用户准备游戏
pomelo.on(events.onBid, function (data) {
    var eve = 'onBid';
    var msg = `playerId: ${data.playerId}, bid: ${data.bid}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：房间' + gameOperate.rid + ' 用户' + data.playerId + ' 选择了下注' + (data.bid / 100) + '元！');
    // gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type] };
});

// 游戏结束
pomelo.on(events.onGameOver, function (data) {
    var eve = 'onGameOver';
    var msg = `msg: ${data.bid}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：房间' + gameOperate.rid + ' 游戏结束：' + JSON.stringify(data));
    // gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type] };
});

// 游戏结算数据
pomelo.on(events.onCalcResult, function (data) {
    var eve = 'onCalcResult';
    var msg = `msg: ${data.player}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：向房间 ' + gameOperate.rid + ' 用户广播结算数据：' + JSON.stringify(data));
    // gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type], coin: data.coin };
    // data = { "1003":{ "coinChange":4141, "tax":84, "coin":21060 },"1004":{ "coinChange": -4225, "tax": 0, "coin": 933453 }}
    for (playerId in data) {
        gameOperate.roomData[playerId].coin = data[playerId].coin;
    }
});

// 玩家1申请上庄
pomelo.on(events.onPlayer1Apply, function (data) {
    gameOperate.msgs = [];
    var eve = 'onPlayer1Apply';
    var msg = `msg: ${data.applyId}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：房间' + gameOperate.rid + ' 当前可申请玩家：' + data.applyId + ' 剩余时间：' + data.checkTime);
    // gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type] };
});

// 玩家2申请上庄
pomelo.on(events.onPlayer2Apply, function (data) {
    var eve = 'onPlayer2Apply';
    var msg = `msg: ${data.applyId}`;
    bold(eve, msg);
    gameOperate.msgs.push('广播：游戏5：房间' + gameOperate.rid + ' 当前可申请玩家：' + data.applyId + ' 剩余时间：' + data.checkTime);
    // gameOperate.roomData[data.playerId] = { playerId: data.playerId, rid: data.rid, type: playerType[data.type] };
});

// ----------------------------------------------------------
// ----------------------------------------------------------
// ----------------------------------------------------------
// ----------------------------------------------------------
// ----------------------------------------------------------
// ----------------------------------------------------------
// ----------------------------------------------------------
// ----------------------------------------------------------

pomelo.on(events.onGameFree, function (data) {
    var eve = 'onGameFree';
    var msg = `checkTime: ${data.checkTime}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
});

pomelo.on(events.onGameStart, function (data) {
    var eve = 'onGameStart';
    var msg = `checkTime: ${data.checkTime}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
});

pomelo.on(events.onGameXiaZhu, function (data) {
    var eve = 'onGameXiaZhu';
    var msg = `checkTime: ${data.checkTime}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
});

pomelo.on(events.onGameKaiPai, function (data) {
    var eve = 'onGameKaiPai';
    var msg = `checkTime: ${data.checkTime}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
});


pomelo.on(events.onGameBid, function (data) {
    var msg = `事件<onGameBid>: playerId: ${data.playerId}`;
    log(msg, data);
});

pomelo.on(events.onCalcResult, function (data) {
    var eve = 'onGameOver';
    var msg = `checkTime: ${data.checkTime}, gameStatus: ${data.gameStatus}`;
    bold(eve, msg);
    log(data);
});

pomelo.on(events.onCancelBanker, function (data) {
    var msg = `事件<onCancelBanker>: playerId: ${data.playerId}`;
    log(msg, data);
});

// console.log('%c123', 'font-weight: bold');
// bold(123);
